<template>
  <div class="roles">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>
        <a href="/hello">首页</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色列表 -->
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="addUserdialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 获取角色列表 -->
      <el-table :data="getRolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 权限列表一 -->
            <el-row
              :class="['BotderBot',index1===0?'BotderTop':'','DivFlex']"
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag @close="handelRemoveItem(scope.row,item1)" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 权限列表二 -->
              <el-col :span="19">
                <el-row
                  :class="[index2===0?'':'BotderTop','DivFlex']"
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      @close="handelRemoveItem(scope.row,item2)"
                      closable
                      type="success"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 权限列表三 -->
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="handelRemoveItem(scope.row,item3)"
                      :disable-transitions="false"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              @click="editRoleInfo(scope.row)"
              type="primary"
              size="mini"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              @click="removeRole(scope.row)"
              type="danger"
              size="mini"
              icon="el-icon-delete"
            >删除</el-button>
            <el-button
              @click="handleRightsShow(scope.row)"
              type="warning"
              size="mini"
              icon="el-icon-setting"
            >权限分配</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog
      @close="removeUserRules"
      title="添加角色"
      :visible.sync="addUserdialogVisible"
      width="50%"
    >
      <!-- 添加角色信息 -->
      <el-form ref="addUserForm" :rules="addUserRules" :model="addUserForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addUserForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addUserForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="postUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog
      @close="removeTreeRights"
      :visible.sync="handleRightsDialogVisible"
      title="分配权限"
      width="50%"
    >
      <!-- <span>这是一段信息</span> -->
      <el-tree
        show-checkbox
        node-key="id"
        default-expand-all
        :data="rightsTree"
        :props="defaultProps"
        :default-checked-keys="treeActiveArr"
        ref="rightsTree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRightsPost">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色信息 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%">
      <el-form ref="editFormInfo" :rules="addUserRules" :model="editFormInfo" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editFormInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editFormInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setEditDialogVisible">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Roles, RolesRights, RightsDealing, AssinRight, AddRole, RemoveRoles, EditRole } from '@/api/api.js'
export default {
  name: 'BackShopRoles',

  data () {
    return {
      // 权限列表
      getRolesList: [],
      // 分配权限列表Show
      handleRightsDialogVisible: false,
      rightsTree: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认自带的系统被选选中的节点
      treeActiveArr: [],
      // 提交角色 同时保存角色id
      defaultUserId: '',
      // 添加角色对话框Show
      addUserdialogVisible: false,
      // 添加角色信息
      addUserForm: {
      },
      // 添加角色正则
      addUserRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入描述信息', trigger: 'blur' },
        ]
      },
      // 编辑角色信息
      editDialogVisible: false,
      // 编辑角色信息
      editFormInfo: {
        roleName: '',
        roleDesc: ''
      }
    };
  },

  created () {
    this.getrolesList()
  },

  methods: {
    // 获取角色权限列表
    async getrolesList () {
      const { data: res } = await Roles();
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error('"获取角色列表失败')
      this.getRolesList = res.data
    },
    // 删除点击所在的权限
    async handelRemoveItem (item1ID, itemID) {
      // 删除权限提示
      let reslut = await this.$messageBox('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (reslut !== 'confirm') return this.$message.info('取消删除权限')
      // 返回一个对象
      const { data: res } = await RolesRights(item1ID.id, itemID.id);
      if (res.meta.status !== 200) return this.$message.info('删除权限失败')
      this.$message.success('删除权限成功！');
      // 删除之后从新赋值data
      item1ID.children = res.data;
    },
    // 获取权限分配
    async handleRightsShow (value) {
      this.handleRightsDialogVisible = true
      const { data: res } = await RightsDealing();
      if (res.meta.status !== 200) return this.$message.error('获取权限树失败！')
      this.rightsTree = res.data;
      // 递归传递参数
      this.threeTreeLsit(value, this.treeActiveArr);
      // 传递id给默认值
      this.defaultUserId = value.id

    },
    // 通过递归方式, 获取角色下所有三级权限的id, 并保存到 treeActiveArr 中
    threeTreeLsit (node, arr) {
      // 判断是否为三级节点 
      // 只有三级节点没有 children 所以取反
      if (!node.children) return arr.push(node.id);
      // 第二次递归
      node.children.forEach(item => this.threeTreeLsit(item, arr))
    },
    // 关闭对话框的同时清空数据
    removeTreeRights () {
      this.treeActiveArr = []
    },
    // 分配权限提交数据
    async handleRightsPost () {
      // 监听被选中节点id
      // 展开运算符
      const RightsList = [
        ...this.$refs.rightsTree.getCheckedKeys(),
        ...this.$refs.rightsTree.getHalfCheckedKeys()
      ];
      // rids	权限 ID 列表（字符串）	
      // 以 , 分割的权限 ID 列表（获取所有被选中、
      // 叶子节点的key和半选中节点的key, 包括 1，2，3级节点）
      const activeStr = RightsList.join(',');
      // :roleId 提交参数 角色 id
      const { data: res } = await AssinRight(this.defaultUserId, { rids: activeStr })
      if (res.meta.status !== 200) return this.$message.error('修改角色权限失败！')
      this.$message.success('修改角色权限成功！')
      // 重新获取数据列表
      this.getrolesList()
      // 关闭树对话框
      this.handleRightsDialogVisible = false;
    },
    // 清除角色提示
    removeUserRules () {
      this.$refs.addUserForm.resetFields()
    },
    // 提交角色信息
    postUserInfo () {
      // 判断用户是否写了信息 没写返回 false
      this.$refs.addUserForm.validate(async validate => {
        if (!validate) return
        const { data: res } = await AddRole(this.addUserForm);
        if (res.meta.status !== 201) return this.$message.error('添加角色失败！');
        this.$message.success('添加角色成功！');
        // 从新获取角色权限列表
        this.getrolesList();
        this.addUserdialogVisible = false
      })

    },
    // 删除角色列表项
    async removeRole (row) {
      const RoleRelust = await this.$messageBox('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (RoleRelust != 'confirm') return this.$message.info('取消删除角色')
      // 确认删除
      const { data: res } = await RemoveRoles(row.id);
      if (res.meta.status !== 200) this.$message.error('删除角色失败')
      // 删除成功从新获取数据
      this.getrolesList()
      this.$message.success('删除角色成功')
    },
    // 编辑角色信息
    editRoleInfo (row) {
      this.editDialogVisible = true;
      // 赋值信息
      this.editFormInfo = row;
    },
    // 编辑角色
    setEditDialogVisible () {
      this.$refs.editFormInfo.validate(async validate => {
        if (!validate) return
        const { data: res } = await EditRole(this.editFormInfo.id, { roleName: this.editFormInfo.roleName, roleDesc: this.editFormInfo.roleDesc });
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error('更新角色信息失败！')
        this.editDialogVisible = false;
        this.$message.success('更新角色信息成功！')
      })
    }
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.BotderTop {
  border-top: 1px solid #eee;
}
.BotderBot {
  border-bottom: 1px solid #eee;
}
// 权限列表垂直居中
.DivFlex {
  display: flex;
  align-items: center;
}
</style>